/** @brief File implementing the scene viewer class.
 *
 * This file contains the implementation of the scene visualiser class.
 *
 * @file Visualisation.cpp
 * @author Johan "Solo" Luisier
 * @date 2013/04/03
 */
#include "Visualisation.hpp"

#include "Core/GridBase.hpp"

#include "UI/RepresentationBase.hpp"

#include <QtCore/qmath.h>

#include <QtGui/QKeyEvent>
#include <QtGui/QWheelEvent>

const qreal Visualisation::ScaleFactor( 1.15 );

Visualisation::Visualisation(GridBase* model, RepresentationBase* scene, QWidget *parent )
    : QGraphicsView( parent )
    , Model( model )
    , Scene( scene )
    , ZoomFactor( 1. )
    , CurrentMode( Default )
{
    //setViewport( new QGLWidget( QGLFormat( QGL::SampleBuffers ) ) );
    setDragMode( QGraphicsView::NoDrag );
    setFocusPolicy( Qt::StrongFocus );

    setHorizontalScrollBarPolicy( Qt::ScrollBarAlwaysOff );
    setVerticalScrollBarPolicy( Qt::ScrollBarAlwaysOff );

    setScene( Scene );

    setSceneRect( QRectF( Scene -> topLeft(), Scene -> bottomRight() ) );
}

Visualisation::~Visualisation()
{}

void Visualisation::wheelEvent( QWheelEvent *event )
{
    /*
    qreal scaling( qPow( ScaleFactor, event -> delta() / 240 ) );

    scale( scaling, scaling );
    */

    if ( event -> delta() > 0. )
    {
        ZoomFactor *= ScaleFactor;
        scale( ScaleFactor, ScaleFactor );
    }
    else
    {
        if ( ZoomFactor / ScaleFactor >= 1. )
        {
            ZoomFactor /= ScaleFactor;
            scale( 1. / ScaleFactor, 1. / ScaleFactor );
        }
    }
}

void Visualisation::keyPressEvent( QKeyEvent* event )
{
    switch ( event -> key() )
    {
    case Qt::Key_Control:
        CurrentMode = Panning;
        setDragMode( QGraphicsView::ScrollHandDrag );
        break;
    case Qt::Key_Shift:
        CurrentMode = Editing;
        setCursor( Qt::PointingHandCursor );
        break;
    default:
        CurrentMode = Default;
        setDragMode( QGraphicsView::NoDrag );
    }
}

void Visualisation::keyReleaseEvent( QKeyEvent* event )
{
    CurrentMode = Default;

    switch ( event -> key() )
    {
    case Qt::Key_Control:
        setDragMode( QGraphicsView::NoDrag );
        break;
    case Qt::Key_Shift:
        setCursor( Qt::ArrowCursor );
        break;
    default:
        break;
    }
}

void Visualisation::mousePressEvent( QMouseEvent* event )
{
    if ( CurrentMode == Editing )
        emit( clickedAt( mapToScene( event -> pos() ) ) );

    QGraphicsView::mousePressEvent( event );
}

void Visualisation::mouseReleaseEvent( QMouseEvent* event )
{
    QGraphicsView::mouseReleaseEvent( event );
}

//void Visualisation::mouseDoubleClickEvent( QMouseEvent* event )
//{
//    emit( clickedAt( mapToScene( event -> pos() ) ) );
//}
